use super::{config, id};
use crate::error::ApiResult;
use crate::oidc::OidcClient;
use crate::{database, logger, server};
use axum::Router;
use sea_orm::DatabaseConnection;
use std::sync::Arc;

#[derive(Clone)]
pub struct AppState {
    pub db_connection: DatabaseConnection,
    pub oidc_client: Arc<OidcClient>,
}

impl AppState {
    fn new(db_connection: DatabaseConnection, oidc_client: Arc<OidcClient>) -> Self {
        Self { db_connection, oidc_client }
    }
}


pub async fn run(router: Router<AppState>) -> ApiResult<()> {
    logger::init();
    tracing::info!("Starting application...");
    id::init()?;

    let db_connection = database::init().await?;
    let oidc_client = OidcClient::new().await?;
    let state = AppState::new(db_connection, oidc_client.clone());

    let server = server::Server::new(config::get().server());
    server.start(state, router).await?;
    Ok(())
}